﻿namespace AutoTest.Common.UtilsHelper
{
    /// <summary>
    /// 重试
    /// </summary>
    public class RetryHelper
    {
        /// <summary>
        /// 重试
        /// </summary>
        /// <param name="action">需要重试的操作</param>
        /// <param name="exceptionAction">异常后操作</param>
        /// <param name="retryCount">重试次数</param>
        /// <returns></returns>
        public static void RetryAction(Action action, Action<Exception>? exceptionAction = null, int retryCount = 5)
        {
            for (int i = 0; i < retryCount; i++)
            {
                try
                {
                    action();
                    break;
                }
                catch (Exception ex)
                {
                    exceptionAction?.Invoke(ex);
                }
            }
        }

        /// <summary>
        /// 重试
        /// </summary>
        /// <param name="action">需要重试的操作</param>
        /// <param name="exceptionAction">异常后操作</param>
        /// <param name="retryCount">重试次数</param>
        /// <returns></returns>
        public static async Task RetryActionAsync(Func<Task> action, Action<Exception>? exceptionAction = null,  int retryCount = 5)
        {
            for (int i = 0; i < retryCount; i++)
            {
                try
                {
                    await action();
                    break;
                }
                catch (Exception ex)
                {
                    exceptionAction?.Invoke(ex);
                }
            }
        }
    }
}
